/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.entity;

import com.jianggujin.dbfly.util.JDBFlyException;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * 排序条件
 * 
 * @author jianggujin
 *
 */
public class JOrderBy {
    protected JEntity entity;
    private JCondition<?> condition;
    private Boolean isProperty;

    protected JOrderBy(JCondition<?> condition, JEntity entity) {
        this.condition = condition;
        this.entity = entity;
    }

    private String property(String property) {
        if (JStringUtils.isEmpty(property) || JStringUtils.isEmpty(property.trim())) {
            throw new JDBFlyException("接收的property为空！");
        }
        property = property.trim();
        if (!this.entity.hasProperty(property)) {
            throw new JDBFlyException("当前实体类不包含名为{}的属性!", property);
        }
        return this.entity.getColumn(property).getColumn();
    }

    public JOrderBy orderBy(String property) {
        String column = property(property);
        if (column == null) {
            isProperty = false;
            return this;
        }
        if (JStringUtils.isNotEmpty(condition.getOrderByClause())) {
            condition.setOrderByClause(condition.getOrderByClause() + ", " + column);
        } else {
            condition.setOrderByClause(column);
        }
        isProperty = true;
        return this;
    }

    public JOrderBy desc() {
        if (isProperty) {
            condition.setOrderByClause(condition.getOrderByClause() + " DESC");
            isProperty = false;
        }
        return this;
    }

    public JOrderBy asc() {
        if (isProperty) {
            condition.setOrderByClause(condition.getOrderByClause() + " ASC");
            isProperty = false;
        }
        return this;
    }

    public JOrderBy orderByAsc(String property) {
        return this.orderBy(property).asc();
    }

    public JOrderBy orderByDesc(String property) {
        return this.orderBy(property).desc();
    }
}